package com.junbao.message.infrastructure.prop;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageResouceReadUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MessageResouceReadUtil.class);
	
    private static Map<String, String> source = new HashMap<String, String>();
    
    static{
		//读取指定位置的配置文档(读取class目录文件)
    	classPathSourceRead("common","redis");
    	//读取磁盘位置的文件	
    	fileSourceRead("common","redis");
    }

    private static void classPathSourceRead(String... configNames){
    	for (String configName : configNames) {
    		//读取指定位置的配置文档(读取class目录文件)
        	try {
    			ResourceBundle rb = ResourceBundle.getBundle(configName);
    			put(rb);
    			LOGGER.info("初始化配置文件classpath:{}成功!",configName);
    		} catch (Exception e) {
    			LOGGER.error("初始化配置文件calsspath:{}失败!",configName);
    		}
		}
    } 
    
    private static void fileSourceRead(String... configNames){
    	for (String configName : configNames) {
    		ResourceBundle rb;
        	BufferedInputStream inputStream = null; 
        	String filePath = new StringBuilder("/opt/junbao/message/").append(configName).append(".properties").toString();
        	try {  
                inputStream = new BufferedInputStream(new FileInputStream(filePath));  
                rb = new PropertyResourceBundle(inputStream);  
                put(rb);
                LOGGER.info("初始化配置文件file:{}成功!",filePath);
            } catch (Exception e) {
            	LOGGER.error("初始化配置文件file:{}失败!",filePath);
            } finally{
            	try {
            		if (inputStream != null) {
            			inputStream.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}  
            }
		}
    }
    
    private synchronized static void put(ResourceBundle rb){
    	if (rb != null) {
    		Set<String> keySet = rb.keySet();
        	for (String key : keySet) {
        		source.put(key, rb.getString(key));
    		}
		}
    }
    /**
     * 根据配置文件中的key查询值
     * @param key
     * @return
     */
    public String get(String key){
    	String msg = null;
    	if (source.containsKey(key)) {
    		msg = source.get(key);
		}
    	return msg;
    }
   
}
